/**
 * adLoader
 * iwebshop的广告加载器
 *
 * 先引入这个js，再load广告，1是广告位的id
 * <code>
 *    <script language="javascript" src="/iwebshop/javascript/adloader/"></script>
 *    <div id="adDiv">广告......</div>
 *    <script language="javascript">(new adLoader()).load(1,"adDiv");</script>
 * </code>
 * @author walu
 */

function medialoader() {
    var _self = this;
    var _id = 0;
    var webUrl = "";
    var positionData = {};
    var adData = {};

    var urlPS = function (url) {
        url = "/" + url + "/";
        return url.replace(/[\/\\]+/g, "/");
    };

    //获取广告位的信息，id广告位id
    this.getPositionInfo = function (id, async) {
        if (!id) {
            return;
        }

        var url = "api/v1/address/" + id;
        var rand = Math.random();
        var args = {'rand': rand};

        $.get(url, args, function (c) {
            if (!c ||  !c.id)
                return;

            positionData = c;
            //设置position的高和宽
            var width, height;
            width = parseInt(positionData.width);
            height = parseInt(positionData.height);
            var element = $("#" + _self.elementID);
            element.css("overflow", 'hidden');
            if (width > 0) {
                element.width(width);
            }
            if (height > 0) {
                element.height(height);
            }
            //稍作修改，传递广告位新id
            _self.getList(positionData.id);
        });
    };

    //获取某个广告位的广告列表，id:广告位id
    this.getList = function (id, async) {
        if (!id ) {
            return;
        }
        var url = "api/v1/ad/" + id;
        var args = {rand: Math.random()};
        $.get(url, args, function (c) {

            if (!c)
                return;

            adData = c;
            _self.next();
        });
    };

    //加载广告
    //id:广告位id
    //async:异步加载机制，如果为true则直接输出，否则等页面加载完成后再输出
    this.load = function (id, elementID, webUrl, async) {
        _self.id = id;
        _self.webUrl = webUrl;
        _self.elementID = elementID;
        _self.async = async || false;

        _self.getPositionInfo(id, async);
    };

    //广告位置div
    this.display = function (index) {

        _self.indexKey = index;
        var ad = adData[index];
        if (!ad) {
            return;
        }

        var width, height, code, title;
        title = (ad.name.length > 0) ? " title='" + ad.name + "' " : " ";
        width = (ad.width !== 0) ? " width='" + ad.width + "' " : " ";
        height = (ad.height !== 0) ? " height='" + ad.height + "' " : " ";
        switch (parseInt(ad['type'])) {
            case 1:
                code = "";
                code += '<a target="_blank" href="{URL}"><img src="{IMG}" alt="{NAME}" ' + width + height + title + '></a>';
                code += '<span><a target="_blank" href="{URL}">' +
                    '<i class="fa fa-arrow-right" aria-hidden="true"></i>进入专题 ' +
                    '</a>' +
                    '</span>';
                code = code.replace(/{URL}/g, ad.url).replace(/{IMG}/g, _self.webUrl + ad.path).replace("{NAME}", ad.name);
                break;
            case 2:
                code = '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" ' + width + height + ' hspace="0" vspace="0" border="0" align="left" id="flashname"><param name="movie" value="{URL}"><param name="quality" value="high"><param name="wmode" value="transparent"><param name="scale" value="noborder"><embed src="{URL}" quality="high" wmode="transparent" scale="noborder" ' + width + height + ' hspace="0" vspace="0" border="0" align="left" name="flashname" type="application/x-shockwave-flash" luginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>';
                code = code.replace(/{URL}/g, ad.ad_path);
                break;
            case 3:
                code = ad.path;
                break;
            case 4:
                code = ad.path;
                break;
            default:
                break;
        }
        //设置div宽度
        //$('#'+_self.elementID).css('cursor','pointer');
        //跳转事宜
        if (ad.url.length > 2) {
            $('#' + _self.elementID).css('cursor', 'pointer');
            $('#' + _self.elementID).click(function () {
                //window.open(ad.url, "_blank");
            });
        }

        //异步与同步加载
        if (_self.async) {
            $(document).ready(function () {
                $('#' + _self.elementID).html(code);
                if (adData.length > 1)
                    setTimeout(function () {
                        _self.next();
                    }, 5000);
            });
        } else {
            $('#' + _self.elementID).html(code);
            if (adData.length > 1)
                setTimeout(function () {
                    _self.next();
                }, 5000);
        }
    };

    this.next = function () {
        var indexKey = _self.indexKey || 0;
        var len = adData.length;
        var index = 0;
        var rand = 0;
        if (positionData.playNum && positionData.playNum == 1) {
            index = (indexKey >= (len - 1)) ? 0 : (indexKey + 1);
        } else {
            rand = parseInt(Math.random() * 1000);
            index = rand % len;
        }

        _self.display(index);
    }
}
